import React, { Component } from 'react'
import "./index.css"

// 创建Context对象
const MyContext = React.createContext()
const {Provider,Consumer} = MyContext

export default class Demo extends Component {
  state ={userName: 'tom', age:18}

  render() {
    const {userName, age} = this.state
    return (
      <div className='parent'>
        <h3>我是A组件</h3>
        <h4>我的用户名是：{this.state.userName}</h4>
        {/* <MyContext.Provider></MyContext.Provider> 或者先解构直接用Provider*/}
        <Provider value={{userName, age}}> {/** 属性必须是value */}
          <B />
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render(){
    return (
      <div className='child'>
        <h3>我是B组件</h3>
        <h4>我是接收A的用户名：{this.props.userName}</h4>
        <C />
        <D />
      </div>
    )
  }
}


class C extends Component {
  static contextType = MyContext  // 谁想要context，谁生命这个属性

  render(){
    console.log(this.context)
    return (
      <div className='grand'>
      <h3>我是C组件</h3>
      <h4>我是接收A的用户名：{this.context.userName}, 年龄是：{this.context.age}</h4>
    </div>
    )
  }
}

function D(){
  return (
    <div className='grand'>
      <h3>我是D组件函数式组件</h3>
      <h4>我是接收A的用户名：
        <Consumer>
          {value => `${value.userName}, 年龄是${value.age}`}
        </Consumer>
      </h4>
    </div>
  )
}